package com.untour.im.client.handler;


import com.untour.im.client.command.ServerPacketDecodec;
import com.untour.im.codec.constants.IMConstants;
import com.untour.im.codec.protocol.message.body.MessageBody;
import com.untour.im.codec.protocol.packet.request.PacketData;
import com.untour.im.codec.protocol.packet.response.header.ResponsePacketHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 消息解码
 */
@Slf4j
public class ServerResponseMessageDecoderHandler extends ByteToMessageDecoder {
//    public static final ServerResponseMessageDecoderHandler INSTANCE = new ServerResponseMessageDecoderHandler();

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        //请求头（
        // 指令
        // 消息解析类型
        // bodylen
        // ）+ 请求体
        if (byteBuf.readableBytes() < IMConstants.SERVER_PROTOCOL_HEADER_LENGTH) {
            return;
        }

        PacketData<ResponsePacketHeader,MessageBody> message = ServerPacketDecodec.INSTANCE.decode(byteBuf);
        if (message == null) {
            log.warn("本次读取数据不完整，下次再读取");
            return;
        }
        out.add(message);
    }
}
